package com.py.credit.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.entity.Column;
import com.py.credit.entity.ColumnResult;
import com.py.credit.entity.DataResult;
import com.py.credit.entity.TableResult;

public class PdfUtils {

	public static class Background extends PdfPageEventHelper {

		private String watermarkPath;

		public Background(String watermark) {
			this.watermarkPath = watermark;

		}

		public Background() {

		}

		@Override
		public void onEndPage(PdfWriter writer, Document document) {

			PdfContentByte canvas = writer.getDirectContentUnder();

			if (watermarkPath != null && new File(watermarkPath).exists()) {

				try {
					Image image = Image.getInstance(watermarkPath);
					image.scaleAbsolute(595, 842);// 自定义大小
					image.setAbsolutePosition(0, 0);
					canvas.addImage(image);
				} catch (Exception e) {

					ExceptionLogger.error(e);
				}

			}

		}
	}

	private static PdfPTable createTable(TableResult tableResult, Document document) throws Exception {

		PdfPTable table = new PdfPTable(4);

		List<Column> columns = tableResult.getColumns();

		List<DataResult> data = tableResult.getData();

		if (columns != null && columns.size() > 0) {

			Font titleFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 15);
			Font columnFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12);
			titleFont.setColor(BaseColor.WHITE);
			PdfPCell cell = new PdfPCell(new Phrase(tableResult.getTableNameCN(), titleFont));

			cell.setHorizontalAlignment(Element.ALIGN_CENTER); // 水平居中
			// cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 垂直居中
			cell.setBorderColor(new BaseColor(229, 229, 229));
			cell.setColspan(4);
			cell.setBackgroundColor(new BaseColor(114, 169, 204));
			cell.setFixedHeight(25);
			table.addCell(cell);
			cell.setColspan(1);
			document.add(table);
			if (data == null || data.size() < 1) {

				PdfPCell nodataCell = new PdfPCell(new Phrase("暂无数据", columnFont));
				PdfPTable recordTable = new PdfPTable(4);
				nodataCell.setColspan(4);
				nodataCell.setBorderColor(new BaseColor(229, 229, 229));
				nodataCell.setFixedHeight(25);
				nodataCell.setBackgroundColor(new BaseColor(255, 255, 255));
				nodataCell.setHorizontalAlignment(Element.ALIGN_CENTER);

				recordTable.addCell(nodataCell);

				recordTable.setSpacingAfter(15);

				document.add(recordTable);

			} else {

				PdfPCell dataAndColumnCell = new PdfPCell();
				dataAndColumnCell.setBorderColor(new BaseColor(229, 229, 229));
				dataAndColumnCell.setMinimumHeight(25);
				dataAndColumnCell.setHorizontalAlignment(Element.ALIGN_CENTER); // 水平居中
				dataAndColumnCell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 垂直居中

				for (DataResult res : data) {

					PdfPTable recordTable = new PdfPTable(4);

					List<ColumnResult> cols = res.getColumns();

					for (ColumnResult col : cols) {

						dataAndColumnCell.setBackgroundColor(new BaseColor(243, 243, 243));
						dataAndColumnCell.setPhrase(new Phrase(col.getMetricName(), columnFont));
						recordTable.addCell(dataAndColumnCell);
						dataAndColumnCell.setBackgroundColor(new BaseColor(255, 255, 255));
						dataAndColumnCell.setPhrase(
								new Phrase(col.getValue() == null ? "" : col.getValue().toString(), columnFont));

						recordTable.addCell(dataAndColumnCell);
					}

					recordTable.setSpacingAfter(15);

					document.add(recordTable);

				}
			}

		}

		return table;

	}

	public static void createCreditCheckPdf(String backgroudimage, String path, String title, String bgbh, String producer,
			String newTitile, Map<String, List<TableResult>> map) throws Exception {
		Document document = new Document(new Rectangle(PageSize.A4));

		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
		Background event = new Background(backgroudimage);
		writer.setPageEvent(event);
		document.open();
		// 标题
		Paragraph titleParagraph = new Paragraph(new Chunk(title == null ? "" : title,
				new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 40)));
		titleParagraph.setAlignment(Element.ALIGN_CENTER);
		titleParagraph.setSpacingAfter(100);
		document.add(titleParagraph);
		long timesatmp = new Date().getTime();

		if (bgbh == null) {

			bgbh = timesatmp + "";
		} else {

			bgbh = timesatmp + bgbh;
		}

		Paragraph numberParagraph = new Paragraph(new Chunk("报告编号: " + bgbh,
				new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 10)));
		numberParagraph.setAlignment(Element.ALIGN_CENTER);
		numberParagraph.setSpacingAfter(250);
		document.add(numberParagraph);
		// 出报告方
		Paragraph producerParagraph = new Paragraph(new Chunk(producer == null ? "报告出具机构": "报告出具机构: "+producer,
				new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 15)));
		producerParagraph.setAlignment(Element.ALIGN_CENTER);
		producerParagraph.setSpacingAfter(10);
		document.add(producerParagraph);
		// 查询日期
		Paragraph queryDateParagraph = new Paragraph(
				new Chunk("报告出具日期: " + DateUtil.getInstance().dateToStr(new Date(), DateUtil.YYYY_MM_DD),
						new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 15)));
		queryDateParagraph.setAlignment(Element.ALIGN_CENTER);
		document.add(queryDateParagraph);

		// 新启一页
		document.newPage();

		if (newTitile != null) {

			org.jsoup.nodes.Document parse = Jsoup.parse("<p>" + newTitile + "</p>");

			Elements elementsByTag = parse.getElementsByTag("p");

			newTitile = elementsByTag.text();

		}

		// 报告声明
		Paragraph statmentParagraph = new Paragraph(new Chunk(newTitile == null ? "" : newTitile,
				new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 15)));

		statmentParagraph.setAlignment(Element.ALIGN_CENTER);
		document.add(statmentParagraph);
		// 新启一页
		document.newPage();

		// 目录开始
		Paragraph contentTextParagraph = new Paragraph(new Chunk("目录",
				new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 40)));
		contentTextParagraph.setAlignment(Element.ALIGN_LEFT);
		contentTextParagraph.setSpacingAfter(20);
		document.add(contentTextParagraph);

		int i = 1;

		for (Entry<String, List<TableResult>> entry : map.entrySet()) {

			List<TableResult> value = entry.getValue();

			if (value != null && value.size() > 0) {

				StringBuilder sb = new StringBuilder();

				String categoryName = value.get(0).getCategoryName();

				for (TableResult table : value) {

					sb.append(table.getTableNameCN()).append("、");

				}

				sb.setLength(sb.length() - 1);

				Paragraph categoryParagraph = new Paragraph(new Chunk(i + "." + categoryName,
						new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 20)));
				categoryParagraph.setAlignment(Element.ALIGN_LEFT);
				categoryParagraph.setSpacingAfter(20);
				Paragraph resourceParagraph = new Paragraph(new Chunk(sb.toString(),
						new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 10)));
				resourceParagraph.setAlignment(Element.ALIGN_LEFT);
				resourceParagraph.setIndentationLeft(20);
				resourceParagraph.setSpacingAfter(20);
				document.add(categoryParagraph);
				document.add(resourceParagraph);

			}

			i++;

		}

		// 新启一页

		document.newPage();
		// 正文开始

		int j = 1;

		for (Entry<String, List<TableResult>> entry : map.entrySet()) {

			List<TableResult> value = entry.getValue();

			if (value != null && value.size() > 0) {

				String categoryName = value.get(0).getCategoryName();

				// 分类
				Paragraph contentTitleParagraph = new Paragraph(new Chunk(
						ArabicToChineseUtils.foematInteger(j) + "、" + categoryName,
						new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 15)));
				contentTitleParagraph.setAlignment(Element.ALIGN_CENTER);
				contentTitleParagraph.setSpacingAfter(10);
				document.add(contentTitleParagraph);

				for (TableResult table : value) {

					createTable(table, document);

				}

			}
			j++;

		}

		document.close();

	}
	
	/**
	 * @Title: mian
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param     设定文件
	 * @return void    返回类型
	 * @throws
	*/

public static void main(String[] args) {
	

		Map<String, List<TableResult>> map = new HashMap<String, List<TableResult>>();
	System.out.println("qweqw");
		try {
			createCreditCheckPdf("getWatermark.png","D:/信用核查报告.pdf", "江河创建集团股份有限公司", "213", "北京市顺义区公共信用信息平台",
					"测试12312",map );
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
